package zjw.dy.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import zjw.dy.datasource.datasource.DataSourceContextHolder;
import zjw.dy.datasource.datasource.DynamicDataSource;
import zjw.dy.datasource.domain.DbInfo;
import zjw.dy.datasource.domain.LogDO;
import zjw.dy.datasource.domain.UserInfo;
import zjw.dy.datasource.services.DBService;
import zjw.dy.datasource.services.LogService;
import zjw.dy.datasource.services.UserService;

import java.util.List;
import java.util.Map;

/**
 * Created by YHYR on 2017-12-25
 */

@SpringBootApplication
public class DynamicApplication implements CommandLineRunner {
    @Autowired
    UserService userService;

    @Autowired
    DBService dbService;

    @Autowired
    LogService logService;

    public static void main(String[] args) {
        SpringApplication.run(DynamicApplication.class, args);
    }

    @Override
    public void run(String... strings) throws Exception {
        /**
         * 获取maste数据库信息
         */
        DataSourceContextHolder.setDBType("default");
        List<UserInfo> userInfoList = userService.list();
        userInfoList.stream().forEach(userInfo -> System.out.println("name is : " + userInfo.getName() + "; sex is : " + userInfo.getSex() + "; age is : " + userInfo.getAge()));


        /**
         * 根据slave数据源获取目标数据库信息
         */
        DataSourceContextHolder.setDBType("master");
        int primayrId = 9;
        DbInfo dbInfo = dbService.getDBInfoByprimayrId(primayrId);
        System.out.println("dbName is -> " + dbInfo.getName());
        dbInfo.setId(null);
        dbService.save(dbInfo);

        DruidDataSource dynamicDataSource = new DruidDataSource();
        dynamicDataSource.setDriverClassName(dbInfo.getDriverClassName());
        dynamicDataSource.setUrl(dbInfo.getHostUrl());
        dynamicDataSource.setUsername(dbInfo.getUsername());
        dynamicDataSource.setPassword(dbInfo.getPassword());

        /**
         * 创建动态数据源
         */
        Map<Object, Object> dataSourceMap = DynamicDataSource.getInstance().getDataSourceMap();
        dataSourceMap.put("dynamic-slave", dynamicDataSource);
        DynamicDataSource.getInstance().setTargetDataSources(dataSourceMap);
        /**
         * 切换为动态数据源实例，打印学生信息
         */
        DataSourceContextHolder.setDBType("dynamic-slave");
        List<LogDO> logDOList = logService.list();
        logDOList.stream().forEach(item -> System.out.println(item));

    }
}
